package com.sas.controller;

import com.sas.common.Result;
import com.sas.entity.Employee;
// 移除不存在的枚举导入，控制器使用整数类型参数
import com.sas.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 员工管理Controller
 */
@RestController
@RequestMapping("/employee")
@Validated
public class EmployeeController {

    private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);
    @Autowired
    private EmployeeService employeeService;

    /**
     * 创建员工
     */
    @PostMapping
    public Result<Employee> createEmployee(@Valid @RequestBody Employee employee) {
        log.info("创建员工: {}", employee.getName());
        try {
            Employee savedEmployee = employeeService.save(employee);
            return Result.success(savedEmployee);
        } catch (Exception e) {
            log.error("创建员工失败", e);
            return Result.error("创建员工失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询员工
     */
    @GetMapping("/{id}")
    public Result<Employee> getEmployeeById(@PathVariable Long id) {
        log.info("查询员工，ID: {}", id);
        Optional<Employee> employee = employeeService.findById(id);
        if (employee.isPresent()) {
            return Result.success(employee.get());
        } else {
            return Result.notFound("员工不存在");
        }
    }

    /**
     * 查询所有员工
     */
    @GetMapping
    public Result<List<Employee>> getAllEmployees(
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer employeeType,
            @RequestParam(required = false) String name) {
        log.info("查询员工列表，状态: {}, 类型: {}, 姓名: {}", status, employeeType, name);
        try {
            List<Employee> employees;
            if (name != null && !name.trim().isEmpty()) {
                employees = employeeService.findByNameContaining(name.trim());
            } else if (status != null) {
                employees = employeeService.findByStatus(status);
            } else if (employeeType != null) {
                employees = employeeService.findByEmployeeType(employeeType);
            } else {
                employees = employeeService.findAll();
            }
            return Result.success(employees);
        } catch (Exception e) {
            log.error("查询员工列表失败", e);
            return Result.error("查询员工列表失败: " + e.getMessage());
        }
    }

    /**
     * 查询在职员工按优先级排序
     */
    @GetMapping("/active")
    public Result<List<Employee>> getActiveEmployees() {
        log.info("查询在职员工按优先级排序");
        try {
            List<Employee> employees = employeeService.findActiveEmployeesOrderByPriority();
            return Result.success(employees);
        } catch (Exception e) {
            log.error("查询在职员工失败", e);
            return Result.error("查询在职员工失败: " + e.getMessage());
        }
    }

    /**
     * 更新员工信息
     */
    @PutMapping("/{id}")
    public Result<Employee> updateEmployee(@PathVariable Long id, @Valid @RequestBody Employee employee) {
        log.info("更新员工信息，ID: {}", id);
        try {
            employee.setId(id);
            Employee updatedEmployee = employeeService.update(employee);
            return Result.success(updatedEmployee);
        } catch (Exception e) {
            log.error("更新员工信息失败", e);
            return Result.error("更新员工信息失败: " + e.getMessage());
        }
    }

    /**
     * 删除员工
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteEmployee(@PathVariable Long id) {
        log.info("删除员工，ID: {}", id);
        try {
            employeeService.deleteById(id);
            return Result.success(null);
        } catch (Exception e) {
            log.error("删除员工失败", e);
            return Result.error("删除员工失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除员工
     */
    @DeleteMapping("/batch")
    public Result<Void> deleteEmployees(@RequestBody List<Long> ids) {
        log.info("批量删除员工，IDs: {}", ids);
        try {
            employeeService.deleteByIds(ids);
            return Result.success(null);
        } catch (Exception e) {
            log.error("批量删除员工失败", e);
            return Result.error("批量删除员工失败: " + e.getMessage());
        }
    }

    /**
     * 获取员工统计信息
     */
    @GetMapping("/statistics")
    public Result<Object> getEmployeeStatistics() {
        log.info("获取员工统计信息");
        try {
            long totalCount = employeeService.count();
            long fullTimeCount = employeeService.countByEmployeeType(1);
            long partTimeCount = employeeService.countByEmployeeType(2);
            long temporaryCount = employeeService.countByEmployeeType(3);
            
            return Result.success(new Object() {
                public final long total = totalCount;
                public final long fullTime = fullTimeCount;
                public final long partTime = partTimeCount;
                public final long temporary = temporaryCount;
            });
        } catch (Exception e) {
            log.error("获取员工统计信息失败", e);
            return Result.error("获取员工统计信息失败: " + e.getMessage());
        }
    }
}